package helper

import (
	"bytes"
	"encoding/json"
	"fmt"
	"runtime"
	"strconv"
	"sync"
	"time"
)

var lock sync.Mutex
var addrMap map[string]*string = make(map[string]*string)

func NowFloat() float64 {
	value := int(time.Now().UnixNano()) / 1e6
	res, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", float64(value)/1000), 64)
	res, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", res), 64)
	return res
}

func JsonEncode(data interface{}) string {
	jsonByte, err := json.Marshal(data)
	if err != nil {
		panic(err.Error())
	}
	return string(jsonByte)
}
func PrintStackTrace(err interface{}) string {
	buf := new(bytes.Buffer)
	fmt.Fprintf(buf, "%v\n", err)
	for i := 1; ; i++ {
		pc, file, line, ok := runtime.Caller(i)
		if !ok {
			break
		}
		fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
	}
	return buf.String()
}

func BuildAddr(IpAddress string, Port float64) *string {
	lock.Lock()
	key := IpAddress + ":" + strconv.Itoa(int(Port))
	connInfo := IpAddress + ":" + strconv.Itoa(int(Port))
	if value, ok := addrMap[key]; !ok {
		value = &connInfo
		addrMap[key] = value
	}
	lock.Unlock()
	return addrMap[key]
}
